import 'dart:async';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geomancy/api/login.dart';
import 'package:geomancy/styles/index.dart';
import 'package:geomancy/widgets/common_btn.dart';
import 'package:geomancy/widgets/common_header.dart';
import 'package:geomancy/widgets/common_input.dart';
import 'package:geomancy/widgets/common_loading_circle.dart';
import 'package:geomancy/widgets/modal_util/index.dart';
import 'package:go_router/go_router.dart';

class PhoneCodeLoginPage extends StatefulWidget {
  const PhoneCodeLoginPage({super.key});

  @override
  State<PhoneCodeLoginPage> createState() => _PhoneCodeLoginPageState();
}

class _PhoneCodeLoginPageState extends State<PhoneCodeLoginPage> {
  String codeTxt = '获取验证码';
  bool isCountingDown = false;
  ///发送期间显示loading图案
  bool loading = false;
  Timer? _timer;
  String? phone;
  String? code;
  bool agreementSelected = false;

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  Future<void> sendCodeHandle() async {
    if (isCountingDown) return;
    if (phone == null || phone?.length != 11) {
      EasyLoading.showToast('请输入正确的手机号');
      return;
    }
    setState(() {
      loading = true;
    });
    try {
      final result = await LoginAPI.getCode(context: context, phone: phone!);
      if (result) {
        setState(() {
          isCountingDown = true;
          codeTxt = '60s';
        });
        int count = 60;
        _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
          count--;
          if (count == 0) {
            setState(() {
              isCountingDown = false;
              codeTxt = '获取验证码';
            });
            timer.cancel();
          } else {
            setState(() {
              codeTxt = '${count}s';
            });
          }
        });
      }
    } finally {
      setState(() {
        loading = false;
      });
    }

  }

  Widget sendCodeWidget() {
    return GestureDetector(
      onTap: sendCodeHandle,
      child: Container(
        width: 200.w,
        height: double.infinity,
        alignment: Alignment.center,
        color: Colors.transparent,
        child: loading
          ? const CommonLoadingCircleWidget()
          : Text(
              codeTxt,
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 30.sp,
                color: isCountingDown ? ColorStyle.textColor.withOpacity(0.5) : ColorStyle.textColor
              )
            ),
      ),
    );
  }

  ///渲染隐私条款弹窗
  Widget renderAgreementWidget() {
    return Container(
      height: 460.w,
      color: Colors.white,
      padding: EdgeInsets.all(40.w),
      child: SafeArea(
        child:  Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text('请阅读并同意以下条款', style: TextStyle(fontSize: 30.sp, color: ColorStyle.textColor)),
            RichText(text: TextSpan(
                style: TextStyle(color: ColorStyle.textColor, fontSize: 30.sp),
                children: [
                  TextSpan(
                    text: '《用户服务协议》',
                    style: TextStyle(color: ColorStyle.red),
                    recognizer: TapGestureRecognizer()..onTap = () {
                      // Routes.navigateTo(context, '/user_agreement');
                    },
                  ),
                  TextSpan(
                    text: '《隐私政策》',
                    style: TextStyle(color: ColorStyle.red),
                    recognizer: TapGestureRecognizer()..onTap = () {
                      // Routes.navigateTo(context, '/private_agreement');
                    },
                  ),
                ]
            )),
            GestureDetector(
              onTap: () {
                setState(() {
                  agreementSelected = true;
                });
                context.pop();
              },
              child: Container(
                height: 80.w,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: ColorStyle.red,
                    borderRadius: BorderRadius.all(Radius.circular(40.w))
                ),
                child: Text('同意并继续', style: TextStyle(fontSize: 30.sp, color: Colors.white)),
              ),
            )
          ],
        ),
      ),
    );
  }

  void getPhoneHandle(String value) {
    setState(() {
      phone = value;
    });
  }
  void getCodeHandle(String value) {
    setState(() {
      code = value;
    });
  }

  Future loginHandle() async {
    if (!agreementSelected) {
      ModalUtil.showBottomModal(
        context: context,
        child: (state) => renderAgreementWidget(),
      );
      return;
    }
    if (phone == null || code == null) {
      return;
    }
    final bool result = await LoginAPI.loginWithCode(
      context: context,
      phone: phone!,
      code: code!,
      mounted: mounted
    );
    if (result && mounted) {
      context.push('/');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CommonHeader.appBar(context: context, showActions: false),
      backgroundColor: ColorStyle.pageDefaultColor,
      resizeToAvoidBottomInset: false,
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Container(
          width: double.infinity,
          padding: EdgeInsets.fromLTRB(80.w, 170.w, 80.w, 80.w),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                width: 260.w,
                height: 260.w,
                decoration: BoxDecoration(
                    border: Border.all(width: 6.w, color: ColorStyle.borderColor),
                    borderRadius: BorderRadius.all(Radius.circular(130.w))
                ),
                child: ClipRRect(
                  borderRadius: BorderRadius.all(Radius.circular(130.w)),
                  child: Image.asset('assets/app_icon.png', fit: BoxFit.fill),
                ),
              ),
              Column(
                children: [
                  Text('手机号登录', style: TextStyle(fontSize: 36.sp, color: ColorStyle.textColor, fontWeight: FontWeight.w400)),
                  SizedBox(height: 30.w),
                  CommonInputWidget(hintText: '请输入手机号', maxLength: 11, keyboardType: TextInputType.phone, getValue: getPhoneHandle),
                  SizedBox(height: 20.w),
                  CommonInputWidget(hintText: '请输入验证码', maxLength: 4, keyboardType: TextInputType.phone, addonAfter: sendCodeWidget(), getValue: getCodeHandle),
                ],
              ),
              SizedBox(
                height: 220.w,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    CommonBtnWidget(txt: '登录', onTap: loginHandle),
                    GestureDetector(
                      onTap: () {
                        setState(() {
                          agreementSelected = !agreementSelected;
                        });
                      },
                      child: Row(
                        children: [
                          Container(
                            width: 30.w,
                            height: 30.w,
                            margin: EdgeInsets.only(right: 12.w),
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              color: agreementSelected ? ColorStyle.themeLightColor : Colors.transparent,
                              border: Border.all(width: 2.w, color: ColorStyle.borderColor),
                              borderRadius: BorderRadius.all(Radius.circular(24.w))
                            ),
                            child: agreementSelected
                              ? Image.asset('assets/icons/icon_picker_confirm.png', width: 16.w)
                              : null
                          ),
                          Expanded(child: RichText(text: TextSpan(
                              style: TextStyle(color: ColorStyle.borderColor, fontSize: 24.sp),
                              children: [
                                const TextSpan(text: '我已阅读并接受'),
                                TextSpan(
                                  text: '《用户服务协议》',
                                  style: TextStyle(color: ColorStyle.red),
                                  recognizer: TapGestureRecognizer()..onTap = () {
                                    context.push('/web_view', extra: {
                                      'url': 'https://fengshui.romko.top/home/user-agreement.html'
                                    });
                                  },
                                ),
                                const TextSpan(text: '及'),
                                TextSpan(
                                  text: '《隐私政策》',
                                  style: TextStyle(color: ColorStyle.red),
                                  recognizer: TapGestureRecognizer()..onTap = () {
                                    context.push('/web_view', extra: {
                                      'url': 'https://fengshui.romko.top/home/private-agreement.html'
                                    });
                                  },
                                ),
                                const TextSpan(text: '并使用本机号码登录。')
                              ]
                          )))
                        ],
                      ),
                    )
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
